#!/bin/bash
###############################################################################
##@Author Nicholas.Zhang
##@Date 2011-04-25
##@Description start application server
###############################################################################
#BASE_BIN_DIR=`dirname $0`
cd `dirname $0`
BASE_BIN_DIR=`pwd`

. $BASE_BIN_DIR/functions.sh

. $BASE_BIN_DIR/env.sh

HOST_NAME=`hostname`
LOG_DIR=$APP_LOG_HOME
LOGS_SAVED=$LOG_DIR/logs_saved
JETTY_STDOUT_LOG=$LOG_DIR/jetty_stdout.log
NGINX_STDOUT_LOG=$LOG_DIR/nginx_stdout.log
PROJECT_LOG=$LOG_DIR/guoguojie.log
KILLWS_LOG=$LOG_DIR/killws.log
JETTY_CTL=$BASE_BIN_DIR/jettyctl.sh
NGINX_CTL=$BASE_BIN_DIR/nginxctl.sh
TIMESTAMP=`date +%Y_%m_%d_%H_%M`

#backup logs
if [ ! -d $LOGS_SAVED ]; then
   mkdir -p $LOGS_SAVED
fi

if [ -f $JETTY_STDOUT_LOG ]; then
   mv -f $JETTY_STDOUT_LOG $LOGS_SAVED/jetty_stdout.log.$TIMESTAMP
fi

if [ -f $NGINX_STDOUT_LOG ]; then
   mv -f $NGINX_STDOUT_LOG $LOGS_SAVED/nginx_stdout.log.$TIMESTAMP
fi

if [ -f $PROJECT_LOG ]; then
   mv -f $PROJECT_LOG $LOGS_SAVED/guoguojie.log.$TIMESTAMP
fi

if [ -f $KILLWS_LOG ]; then
   mv -f $KILLWS_LOG $LOGS_SAVED/killws.log.$TIMESTAMP
fi

java_pid=`ps  --no-heading -C java -f --width 1000 | grep "$JETTY_SERVER_DIR" |awk '{print $2}'`
if [ ! -z "$java_pid" ]; then
    echo "Jetty server already started: pid=$java_pid"
    exit;
fi    

start_jetty(){
    echo -e "$HOST_NAME: starting jetty ...\c"
    $JETTY_CTL > $JETTY_STDOUT_LOG 2>&1 &
    COUNT=0
    printProcess 5
    while [ $COUNT -lt 1 ]; do    
        COUNT=`curl -s $CHECK_STARTUP_URL |grep -c "$STARTUP_SUCCESS_MSG"`
        printProcess 3        
    done
    success "Oook!"
}

start_nginx(){
    echo -e "$HOST_NAME: starting nginx ...\c"
    $NGINX_CTL > $NGINX_STDOUT_LOG 2>&1 &
    success "Oook!"    
}

start_jetty
start_nginx
success "$HOSTNAME: startup web server done!"
